﻿using System;
using System.Windows.Forms;
using MessageHandler;

namespace Chatclient
{
	public partial class FormProfile : Form
	{
		private Controller controller;
		private bool changeProfile;
		private UserInfo userInfo;

		public UserInfo UserInfo
		{
			get { return userInfo; }
		}

		public FormProfile(Controller controller, UserInfo userInfo, bool changeProfile)
		{
			this.controller = controller;
			this.controller.MessageReceived += new Controller.MessageReceivedEventHandler(controller_MessageReceived);
			this.userInfo = userInfo;
			this.changeProfile = changeProfile;
			this.Text = "Profil " + userInfo.username;
			InitializeComponent();
			InitUIElements();
			this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
		}

		private void InitUIElements()
		{
			this.btnSave.Visible = this.changeProfile;
			btnCancel.Text = changeProfile ? "Abbrechen" : "OK";
			txtBxfirstName.ReadOnly = !changeProfile;
			txtBxLastName.ReadOnly = !changeProfile;
			dtPickerBirthday.Enabled = changeProfile;
			rBtnFemale.Enabled = changeProfile;
			rBtnMale.Enabled = changeProfile;
		}

		void controller_MessageReceived(object sender, MessageReceivedEventArgs e)
		{
			switch (e.Message.messageType)
			{
				case MessageType.PROFILEUPDATE:
					ShowProfile(((ProfileUpdateMessageType)e.Message.Item).userInfo);
					break;
				default:
					break;
			}
		}

		private void FormProfile_Load(object sender, EventArgs e)
		{
			ShowProfile(this.userInfo);
			if (!changeProfile)
			{
				controller.UpdateProfile(userInfo);
			}
		}

		private delegate void ShowProfileCallback(UserInfo userInfo);
		private void ShowProfile(UserInfo userInfo)
		{
			if (this.InvokeRequired)
			{
				Invoke(new ShowProfileCallback(ShowProfile), userInfo);
			}
			else
			{
				txtBxUsername.Text = userInfo.username;
				txtBxfirstName.Text = userInfo.firstname;
				txtBxLastName.Text = userInfo.lastname;
				if (userInfo.birthdaySpecified)
				{
					dtPickerBirthday.Value = userInfo.birthday;
				}
				rBtnMale.Checked = userInfo.gender;
				rBtnFemale.Checked = !userInfo.gender;
			}
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
			userInfo.birthday = dtPickerBirthday.Value;
			userInfo.birthdaySpecified = true;
			userInfo.firstname = txtBxfirstName.Text;
			userInfo.lastname = txtBxLastName.Text;
			userInfo.gender = rBtnMale.Checked;
			userInfo.genderSpecified = true;
			this.DialogResult = System.Windows.Forms.DialogResult.OK;
		}

		private void FormProfile_FormClosed(object sender, FormClosedEventArgs e)
		{
			controller.MessageReceived -= controller_MessageReceived;
		}
	}
}
